package bank;

public class _63UniquePathsWithObstacles {
    public static int uniquePathsWithObstacles(int[][] obstacleGrid) {
        if (obstacleGrid[0][0] == 1){
            return 0;
        }
        int[][] dp = new int[obstacleGrid.length+1][obstacleGrid[0].length+1];
        dp[1][1] = 1;
        for (int i = 1;i < dp.length;i++){
            for (int j = 1;j < dp[0].length;j++){
                if (obstacleGrid[i-1][j-1] == 1){
                    //  如果该位置有障碍物，直接跳过
                    continue;
                }
                if ((i == 1 && j != 1) || (i != 1 && j == 1)){
                    dp[i][j] = dp[i-1][j] + dp[i][j-1];
                    continue;
                }
                if ((j > 1 && obstacleGrid[i-1][j-2] == 1) && (obstacleGrid[i-2][j-1] == 0)){
                    //  左边有障碍物,上边没有
                    dp[i][j] = dp[i-1][j];
                }else if ((j > 1 && obstacleGrid[i-1][j-2] == 0) && (obstacleGrid[i-2][j-1] == 1)){
                    //  上边有障碍物,左边没有
                    dp[i][j] = dp[i][j-1];
                }else if(i != 1 && j != 1){
                    dp[i][j] = dp[i-1][j] + dp[i][j-1];
                }
            }
        }
        return dp[obstacleGrid.length][obstacleGrid[0].length];
    }
}
